package com.linhui.consumer.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.linhui.common.model.User;
import com.linhui.common.service.UserService;
import com.linhui.rpc.model.RpcRequest;
import com.linhui.rpc.model.RpcResponse;
import com.linhui.rpc.serializer.Serializer;
import com.linhui.rpc.serializer.imp.JDKSerializer;

import java.io.IOException;

/**
 * @author: 临晖
 * @since: 2024-05-10
 */
public class UserServiceProxy implements UserService {
    private static final String REQUEST_ADDRESS = "http://localhost:8080";
    @Override
    public User getUser(User user) {
        //指定序列化器
        Serializer serializer = new JDKSerializer();
        //发请求 - 封装请求参数
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setArgs(new Object[]{user});
        rpcRequest.setParameterTypes(new Class[]{user.getClass()});
        rpcRequest.setMethodName("getUser");
        rpcRequest.setServiceName(UserService.class.getName());
        try {
            byte[] bytes = serializer.serialize(rpcRequest);
            byte[] result;

            HttpResponse httpResponse = HttpRequest.post(REQUEST_ADDRESS).body(bytes).execute();

            result = httpResponse.bodyBytes();

            //反序列化
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (User)rpcResponse.getData();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
